//
//  LMPostController.m
//  舍品
//
//  Created by 楼 眉 on 16/2/23.
//  Copyright © 2016年 楼 眉. All rights reserved.
//

#import "LMPostController.h"
#import "LMTextViewPlus.h"
#import "LMPost.h"
#import <ReactiveCocoa.h>
#import "LMAlertLabel.h"
#import "LMImage.h"
#import "LMWarningLabel.h"
static int const TextViewSpace = 10;

@interface LMPostController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIScrollViewDelegate,UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)  UIView  *topView;
@property (nonatomic,strong)  UIScrollView *bgView;
@property (nonatomic,strong)  UITextField *titleTf;

@property (nonatomic,strong)  UIScrollView  *bottomView;
@property (nonatomic,strong)  NSArray *btnNames;

@property (nonatomic,strong)  UIImageView *addImageView;
@property (nonatomic,strong)  UIView *bottomBgView;
@property (nonatomic,strong)  LMTextViewPlus *lmTv;
@property (nonatomic,assign) CGRect keyBoardFrame;
@property (nonatomic,assign) CGPoint tempPoint;

@end

@implementation LMPostController

- (void)setKeyBoardFrame:(CGRect)keyBoardFrame
{
    _keyBoardFrame = keyBoardFrame;
    for (UIView *lm in self.view.subviews) {
        if ([lm isKindOfClass:[LMAlertLabel class]]) {
            lm.y -= 80;
    }
    }
}
- (NSArray *)btnNames
{
    if (_btnNames == nil) {
        _btnNames = @[@"写文字",@"加图片",@"传视频"];
    }
    return _btnNames;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupPostSubViews];
    //监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

- (void)keyboardWillChangeFrameNotification:(NSNotification *)note
{
    //取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
//    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //取得键盘最后的frame(根据userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";)
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keyBoardFrame = keyboardFrame;
}
- (void)setupPostSubViews
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    UIView *topView = [[UIView alloc]init];
    topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 20*kUnit + 44*kUnit);
    topView.backgroundColor =  KMainColor;
    [self.view addSubview:topView];
    
    UILabel *topLabel = [[UILabel alloc]init];
    topLabel.text = @"我要发帖";
    topLabel.textAlignment = NSTextAlignmentCenter;
    topLabel.textColor = [UIColor blackColor];
    topLabel.frame = CGRectMake(0, 0, 100*kUnit, 33*kUnit);
    topLabel.center = topView.center;
    topLabel.y = topView.height - topLabel.height - 5;
    [topView addSubview: topLabel];
    
    UIButton *backBtn = [[UIButton alloc]init];
    backBtn.frame = CGRectMake(0, topLabel.y, 50, 33);
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    [backBtn setTitleColor:KSetOffColor forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    UIButton *issueBtn = [[UIButton alloc]init];
    issueBtn.frame = CGRectMake(topView.width - 50, topLabel.y, 50, 33);
    [issueBtn setTitle:@"发布" forState:UIControlStateNormal];
    [issueBtn setTitleColor:KSetOffColor forState:UIControlStateNormal];
    [issueBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [issueBtn addTarget:self action:@selector(issueBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:issueBtn];
    
    UIScrollView *bgView = [[UIScrollView alloc]init];
    bgView.frame = CGRectMake(0, CGRectGetMaxY(topView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - topView.height);
    bgView.backgroundColor = RGBCOLOR(220, 220, 220);
    bgView.delegate = self;
    bgView.alwaysBounceVertical = YES;
    self.bgView = bgView;
    [self.view addSubview:bgView];
    
    UITextField *titleTf = [[UITextField alloc]init];
    titleTf.frame = CGRectMake(10, 20, SCREEN_WIDTH - 20, 33);
    titleTf.placeholder = @"请输入标题(6~30个字之间)";
    titleTf.backgroundColor = [UIColor whiteColor];
    titleTf.textColor = [UIColor lightGrayColor];
    titleTf.delegate = self;
    self.titleTf = titleTf;
    [bgView addSubview:titleTf];
    
    UIView *bottomBgView = [[UIView alloc]init];
    bottomBgView.frame = CGRectMake(10, CGRectGetMaxY(titleTf.frame), SCREEN_WIDTH - 20, 0);
    self.bottomBgView = bottomBgView;
    [bgView addSubview:bottomBgView];
    
    UIScrollView *bottomView = [[UIScrollView alloc]init];
    bottomView.frame = CGRectMake(0, self.view.height - 44, SCREEN_WIDTH, 44);
    bottomView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    CGFloat btnY = 0;
    CGFloat btnW = bottomView.width / 3;
    CGFloat btnH = bottomView.height;
    
    for (int index = 0; index < 3; index ++) {
        CGFloat btnX = btnW *index;
        UIButton *btn  = [[UIButton alloc]init];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        NSString *text = self.btnNames[index];
        [btn setTitle:text forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
        btn.backgroundColor = KMainColor;
        btn.tag = 100 + index;
        [btn addTarget:self action:@selector(toolBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
    }
}

#pragma mark - 三个不同按钮点击
- (void)toolBtnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 100:
            [self addText];
            break;
            case 101:
            [self addPicture];
            break;
            case 102:
            [self addVideo];
            break;
    }
}

- (void)deleteBtnClick
{
}

#pragma mark - 插入文字内容
- (void)addText
{
    LMTextViewPlus *lmTv = [[LMTextViewPlus alloc]init];
    lmTv.textView.font = [UIFont systemFontOfSize:15];
    [[lmTv rac_signalForSelector:@selector(deleteBtnClick)] subscribeNext:^(id x) {
          [lmTv removeFromSuperview];
        [self layoutBottomBgViewSubViews];
    }];
    
    
    lmTv.textView.delegate = self;
    [self.bottomBgView addSubview:lmTv];
    [self layoutBottomBgViewSubViews];
    [self calculateBgViewContentOffset];
}

#pragma mark - 插入图片内容
- (void)addPicture;
{
//    __weak typeof(self) weakSelf = self;
//    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"从哪取图" message:nil preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    [alertVc addAction:cancelAction];
//    
//    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"从相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePc = [[UIImagePickerController alloc]init];
        imagePc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePc.delegate = self;
        [self presentViewController:imagePc animated:YES completion:^{
//            
        }];
//    }];
//    [alertVc addAction:cameraAction];
//    
//    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        UIImagePickerController *imagePc = [[UIImagePickerController alloc]init];
//        imagePc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//        imagePc.delegate = weakSelf;
//        [weakSelf presentViewController:imagePc animated:YES completion:^{
//            
//        }];
//    }];
//    [alertVc addAction:albumAction];
//    
//    [self presentViewController:alertVc animated:YES completion:^{
//        
//    }];
    
 
}

#pragma mark - 插入视频内容
- (void)addVideo
{
    [LMWarningLabel LM_createWarningLabelWithTitle:@"暂不支持该功能"];
}

- (void)backBtnClick
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//计算bgView的位移
- (void)calculateBgViewContentOffset
{
    if (self.bottomBgView.subviews.count > 2) {
        CGPoint offset = self.bgView.contentOffset;
        offset.y = CGRectGetMaxY(self.bottomBgView.frame) - (SCREEN_HEIGHT - 20 - 44 - 49);
        [self.bgView setContentOffset:offset animated:YES];
    }
}

- (void)layoutBottomBgViewSubViews
{
//    CGFloat viewX = 0;
//    CGFloat viewW = self.bottomBgView.width;
//    CGFloat viewH = 180;
//
//    for ( int index = 0; index < self.bottomBgView.subviews.count; index ++) {
//        if (index < 0) index =0;
//        UIView *view = self.bottomBgView.subviews[index];
//        CGFloat viewY = index *viewH + TextViewSpace;
//        view.frame = CGRectMake(viewX, viewY, viewW, viewH - TextViewSpace);
//    }
    CGFloat viewX = 0;
    CGFloat viewY = 10;
    CGFloat viewW = SCREEN_WIDTH - 20;
    CGFloat viewH = 0;
    if (self.bottomBgView.subviews)
    {
        
        for (int index = 0; index < self.bottomBgView.subviews.count; index ++)
        {
            int lastViewIndex = index - 1;
            if (!(lastViewIndex  < 0)) {
                UIView *tempView = self.bottomBgView.subviews[lastViewIndex];
                viewY = CGRectGetMaxY(tempView.frame) + 10;
            }
            UIView *view = self.bottomBgView.subviews[index];
            if ([view isKindOfClass:[LMTextViewPlus class]]) {
                viewH = 180;
            }else
            {
                UIImageView *imageView = (UIImageView *)view;
                viewH = imageView.image.size.height;
            }
            view.frame = CGRectMake(viewX, viewY, viewW, viewH);
        }
        
    }

    //计算背景bottomBgView的高度
    if (self.bottomBgView.subviews.count == 0) {
        self.bottomBgView.height = 0;
    }
    for (UIView *view in self.bottomBgView.subviews) {
        self.bottomBgView.height = CGRectGetMaxY(view.frame);
    }
    
    self.bgView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.bottomBgView.frame) + 20 + self.titleTf.height);
}
/*
  发布按钮点击
*/
- (void)issueBtnClick
{
    //结束编辑
    [self.view endEditing:YES];
    //检查各输入控件状态以便判断能否上传
    NSMutableArray *conArray = [NSMutableArray array];
    for (UIView *view in self.bottomBgView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView *)view;
            [conArray addObject:imageView];
        }else
        {
            LMTextViewPlus *lmTv = (LMTextViewPlus *)view;
            if (lmTv.textView.text.length > 0) {
                [conArray addObject:lmTv.textView.text];
            }
        }
    }
    if (self.titleTf.text.length == 0) {
        [LMAlertLabel alertLabelWithTarget: self title:@"标题不能为空"];
        return;
    }else if (self.titleTf.text.length < 6)
    {
        [LMAlertLabel alertLabelWithTarget: self title:@"标题字数大于6"];
        return;
    }else if (conArray.count == 0)
    {
        [LMAlertLabel alertLabelWithTarget: self title:@"请写入帖子内容"];
        return;
    }
    
    //遍历控件上传帖子内容
    [SVProgressHUD showWithStatus:@"发帖中"];
    dispatch_queue_t  myqueue = dispatch_queue_create("for uploading images", DISPATCH_QUEUE_SERIAL);
    NSMutableArray *contents = [NSMutableArray array];
    LMPost *post = [LMPost object];
    LMUser *user = [LMUser currentUser];
    post.title = self.titleTf.text;
    for (UIView *view in self.bottomBgView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView *)view;
            double scale = imageView.image.size.width / imageView.image.size.height;
            NSString *scaleString = [NSString stringWithFormat:@"%f",scale];
            NSData *data = UIImagePNGRepresentation(imageView.image);
            AVFile *file = [AVFile fileWithData:data];
            dispatch_async(myqueue, ^{
                [file save];
                NSDictionary *ImageDict = @{@"image":file.url,@"scale":scaleString};
                [contents addObject:ImageDict];
            });
        }
        else
        {
            dispatch_async(myqueue, ^{
                LMTextViewPlus *lmtv = (LMTextViewPlus *)view;
                NSDictionary *textDict = @{@"text":lmtv.textView.text};
                [contents addObject:textDict];
            });
        }
    }
    dispatch_async(myqueue, ^{
        AVRelation *relation = [user relationForKey:@"posts"];
        post.contentArray = contents;
        post.writer = user;
        __weak typeof(self) weakSelf = self;
        [post saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [relation addObject:post];
                [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if ( succeeded) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                            [LMAlertLabel alertLabelWithTarget:self title:@"发帖子成功"];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                            });
                        });
                    }
                }];
            }
        }];
    });
    
}
#pragma marks - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImageView *addImageView = [[UIImageView alloc]init];
    addImageView.userInteractionEnabled = YES;
    self.addImageView = addImageView;
    LMImage* original = [info objectForKey:UIImagePickerControllerOriginalImage];
//    UIImage *smallImage = [LMImage imageWithImageSimple:original scaledToSize:CGSizeMake(120, 120)];
//    UIImage *middleImage = [LMImage imageWithImageSimple:original scaledToSize:CGSizeMake(210, 210)];
    double scale = 1.0f;
    if (original) {
        scale = original.size.width / original.size.height;
    }
    CGFloat bigImageW = SCREEN_WIDTH - 10;
    CGFloat bigImageH = bigImageW / scale;
    UIImage *bigImage = [LMImage imageWithImageSimple:original scaledToSize:CGSizeMake(bigImageW,bigImageH)];
    addImageView.image = bigImage;
    addImageView.frame = CGRectMake(0,10,bigImage.size.width - 30, bigImage.size.height);
    UIView *lastView = [self.bottomBgView.subviews lastObject];
    if (lastView) {
        addImageView.y = CGRectGetMaxY(lastView.frame) + TextViewSpace;
    }
    UIButton *shanchuBtn = [[UIButton alloc]init];
    shanchuBtn.frame = CGRectMake(0, 0, 55*kUnit, 33*kUnit);
    shanchuBtn.x =  addImageView.width - 55*kUnit + 20*kUnit;
    shanchuBtn.y = addImageView.height - 33*kUnit - 5*kUnit;
    shanchuBtn.backgroundColor = [UIColor lightGrayColor];
    [shanchuBtn setTitle:@"删除" forState:UIControlStateNormal];
    [shanchuBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [shanchuBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    shanchuBtn.alpha = 0.5;
    [addImageView addSubview:shanchuBtn];
    [shanchuBtn addTarget:self action:@selector(shanchuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomBgView addSubview:addImageView];
    [self layoutBottomBgViewSubViews];
    [self calculateBgViewContentOffset];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)shanchuBtnClick:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    [btn.superview removeFromSuperview];
    [self layoutBottomBgViewSubViews];
    [self calculateBgViewContentOffset];
}
#pragma marks - UITextView Delegate
//一点击输入框就调整输入框的位置
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    
    LMTextViewPlus *lmTv = (LMTextViewPlus *)textView.superview;
    CGPoint offset = self.bgView.contentOffset;
    self.tempPoint = offset;
    int index = (lmTv.y - 10) / lmTv.height;
    if (index == 0) {
        offset.y = CGRectGetMaxY(self.titleTf.frame);
    }else
    {
        offset.y = CGRectGetMaxY(self.titleTf.frame) + (lmTv.height + 10) *index;
    }
        [self.bgView setContentOffset:offset];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [self.bgView setContentOffset:self.tempPoint];
}
#pragma mark -  UITextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.bgView setContentOffset:CGPointMake(0, 0) animated:NO];
}
#pragma mark - 规定能输入字符串的个数
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= 15 && range.length == 0) {
        return NO;
    }
    return YES;
}

#pragma marks - warning
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - dealloc
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"dealloc--postVc");
}
@end
